//
//  CustomUtilities.m
//  test_simple_project
//
//  自定义工具类实现 - 完全可混淆
//

#import "CustomUtilities.h"
#import <CommonCrypto/CommonDigest.h>

// 自定义私有常量 - 可混淆
static NSString * const kCustomEncodingKey = @"CustomSecretKey2024";
static NSString * const kCustomEmailPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$";
static NSString * const kCustomPhonePattern = @"^\\+?[1-9]\\d{1,14}$";

@implementation CustomUtilities

#pragma mark - String Processing (可混淆)

+ (NSString *)customEncodeString:(NSString *)input {
    if (!input || input.length == 0) {
        return @"";
    }
    
    NSData *customInputData = [input dataUsingEncoding:NSUTF8StringEncoding];
    NSString *customEncodedString = [customInputData base64EncodedStringWithOptions:0];
    
    // 简单的自定义编码
    NSMutableString *customResult = [[NSMutableString alloc] init];
    for (NSInteger i = 0; i < customEncodedString.length; i++) {
        unichar customChar = [customEncodedString characterAtIndex:i];
        [customResult appendFormat:@"%c", customChar + 1];
    }
    
    return [customResult copy];
}

+ (NSString *)customDecodeString:(NSString *)encoded {
    if (!encoded || encoded.length == 0) {
        return @"";
    }
    
    // 反向自定义解码
    NSMutableString *customDecoded = [[NSMutableString alloc] init];
    for (NSInteger i = 0; i < encoded.length; i++) {
        unichar customChar = [encoded characterAtIndex:i];
        [customDecoded appendFormat:@"%c", customChar - 1];
    }
    
    NSData *customDecodedData = [[NSData alloc] initWithBase64EncodedString:customDecoded options:0];
    return [[NSString alloc] initWithData:customDecodedData encoding:NSUTF8StringEncoding];
}

+ (NSString *)customHashString:(NSString *)input {
    if (!input) {
        return @"";
    }
    
    const char *customCString = [input UTF8String];
    unsigned char customDigest[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(customCString, (CC_LONG)strlen(customCString), customDigest);
    
    NSMutableString *customHashString = [[NSMutableString alloc] init];
    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [customHashString appendFormat:@"%02x", customDigest[i]];
    }
    
    return [customHashString copy];
}

+ (BOOL)customValidateEmail:(NSString *)email {
    if (!email || email.length == 0) {
        return NO;
    }
    
    NSPredicate *customEmailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", kCustomEmailPattern];
    return [customEmailPredicate evaluateWithObject:email];
}

#pragma mark - Data Processing (可混淆)

+ (NSArray *)customSortArray:(NSArray *)array ascending:(BOOL)ascending {
    if (!array || array.count == 0) {
        return @[];
    }
    
    NSSortDescriptor *customSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:ascending];
    return [array sortedArrayUsingDescriptors:@[customSortDescriptor]];
}

+ (NSDictionary *)customGroupArray:(NSArray *)array byKey:(NSString *)key {
    if (!array || !key) {
        return @{};
    }
    
    NSMutableDictionary *customGroupedDict = [[NSMutableDictionary alloc] init];
    
    for (id customItem in array) {
        if ([customItem respondsToSelector:NSSelectorFromString(key)]) {
            id customKeyValue = [customItem valueForKey:key];
            NSString *customGroupKey = [customKeyValue description];
            
            NSMutableArray *customGroupArray = customGroupedDict[customGroupKey];
            if (!customGroupArray) {
                customGroupArray = [[NSMutableArray alloc] init];
                customGroupedDict[customGroupKey] = customGroupArray;
            }
            
            [customGroupArray addObject:customItem];
        }
    }
    
    return [customGroupedDict copy];
}

+ (NSData *)customSerializeObject:(id)object {
    if (!object) {
        return nil;
    }
    
    NSError *customError = nil;
    NSData *customSerializedData = [NSJSONSerialization dataWithJSONObject:object
                                                                   options:NSJSONWritingPrettyPrinted
                                                                     error:&customError];
    
    if (customError) {
        NSLog(@"Custom serialization error: %@", customError.localizedDescription);
        return nil;
    }
    
    return customSerializedData;
}

+ (id)customDeserializeData:(NSData *)data {
    if (!data) {
        return nil;
    }
    
    NSError *customError = nil;
    id customDeserializedObject = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:NSJSONReadingMutableContainers
                                                                    error:&customError];
    
    if (customError) {
        NSLog(@"Custom deserialization error: %@", customError.localizedDescription);
        return nil;
    }
    
    return customDeserializedObject;
}

#pragma mark - Calculation Tools (可混淆)

+ (double)customCalculateDistance:(CGPoint)point1 to:(CGPoint)point2 {
    double customDeltaX = point2.x - point1.x;
    double customDeltaY = point2.y - point1.y;
    return sqrt(customDeltaX * customDeltaX + customDeltaY * customDeltaY);
}

+ (NSInteger)customGenerateRandomNumber:(NSInteger)min max:(NSInteger)max {
    if (min >= max) {
        return min;
    }
    
    NSInteger customRange = max - min + 1;
    return min + arc4random_uniform((uint32_t)customRange);
}

+ (NSString *)customFormatFileSize:(long long)bytes {
    if (bytes < 1024) {
        return [NSString stringWithFormat:@"%lld B", bytes];
    } else if (bytes < 1024 * 1024) {
        return [NSString stringWithFormat:@"%.1f KB", bytes / 1024.0];
    } else if (bytes < 1024 * 1024 * 1024) {
        return [NSString stringWithFormat:@"%.1f MB", bytes / (1024.0 * 1024.0)];
    } else {
        return [NSString stringWithFormat:@"%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0)];
    }
}

#pragma mark - Validation Tools (可混淆)

+ (BOOL)customIsValidPhoneNumber:(NSString *)phone {
    if (!phone || phone.length == 0) {
        return NO;
    }
    
    NSPredicate *customPhonePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", kCustomPhonePattern];
    return [customPhonePredicate evaluateWithObject:phone];
}

+ (BOOL)customIsValidCreditCard:(NSString *)cardNumber {
    if (!cardNumber || cardNumber.length == 0) {
        return NO;
    }
    
    // 移除空格和连字符
    NSString *customCleanedNumber = [[cardNumber componentsSeparatedByCharactersInSet:
                                     [NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:@""];
    customCleanedNumber = [[customCleanedNumber componentsSeparatedByString:@"-"] componentsJoinedByString:@""];
    
    // 简单的长度验证
    return customCleanedNumber.length >= 13 && customCleanedNumber.length <= 19;
}

+ (NSString *)customSanitizeInput:(NSString *)input {
    if (!input || input.length == 0) {
        return @"";
    }
    
    // 移除潜在的危险字符
    NSMutableString *customSanitized = [input mutableCopy];
    [customSanitized replaceOccurrencesOfString:@"<" withString:@"&lt;" options:0 range:NSMakeRange(0, customSanitized.length)];
    [customSanitized replaceOccurrencesOfString:@">" withString:@"&gt;" options:0 range:NSMakeRange(0, customSanitized.length)];
    [customSanitized replaceOccurrencesOfString:@"&" withString:@"&amp;" options:0 range:NSMakeRange(0, customSanitized.length)];
    [customSanitized replaceOccurrencesOfString:@"\"" withString:@"&quot;" options:0 range:NSMakeRange(0, customSanitized.length)];
    [customSanitized replaceOccurrencesOfString:@"'" withString:@"&#x27;" options:0 range:NSMakeRange(0, customSanitized.length)];
    
    return [customSanitized copy];
}

@end
